package com.yidi.system.service.imp;

import com.yidi.common.core.service.imp.AbstractBaseService;
import com.yidi.common.core.text.Convert;
import com.yidi.common.enums.RemoveEnum;
import com.yidi.common.utils.StringUtils;

import com.yidi.system.domain.SysNotice;
import com.yidi.system.repository.SysNoticeRepository;
import com.yidi.system.service.SysNoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：Xn
 * @ClassName: SysNoticeServiceImpl
 * @date ：2021-10-19 14:16
 * @describe ：
 */
@Service
public class SysNoticeServiceImpl extends AbstractBaseService<SysNotice> implements SysNoticeService {

    @Autowired
    private SysNoticeRepository sysNoticeRepository;

    /**
     * 分页
     */
    @Override
    public Page<SysNotice> findByPage(Integer pageNo, Integer pageSize, SysNotice notice) {
        List<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.DESC, "createTime"));
        Sort sort = Sort.by(orders);
        Pageable pageable = PageRequest.of(pageNo, pageSize, sort);

        Page<SysNotice> page = sysNoticeRepository.findAll((root, query, cb) ->{
            List<Predicate> list = new ArrayList<>();
            list.add(cb.and(cb.equal(root.get("removeStatus").as(Integer.class), RemoveEnum.NOT_REMOVE.getCode())));

            if(StringUtils.isNotBlank(notice.getNoticeTitle())) {
                list.add(cb.and(cb.like(root.get("noticeTitle").as(String.class), notice.getNoticeTitle())));
            }

            if(StringUtils.isNotBlank(notice.getNoticeType())) {
                list.add(cb.and(cb.equal(root.get("noticeType").as(String.class), notice.getNoticeType())));
            }

            if(StringUtils.isNotBlank(notice.getCreateBy())) {
                list.add(cb.and(cb.like(root.get("createBy").as(String.class), notice.getCreateBy())));
            }

            Predicate[] p = new Predicate[list.size()];
            return cb.and(list.toArray(p));
        },pageable);

        return page;
    }

    @Override
    public void updateNotice(SysNotice notice) {
        SysNotice n = findById(notice.getId());

        n.setNoticeTitle(notice.getNoticeTitle());
        n.setNoticeType(notice.getNoticeType());
        n.setNoticeContent(notice.getNoticeContent());
        n.setStatus(notice.getStatus());

        modify(n);
    }

    /**
     * 删除公告对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public void deleteNoticeByIds(Long[] ids)
    {
        for(Long id : ids) {
            remove(id);
        }
    }
}
